<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}

			.date {
				width: 300px;
				height: 220px;
				border: 1px solid #000;
				margin: 100px auto;
			}

			.title {
				width: 200px;
				display: flex;
				font-size: 12px;
				margin: auto;
				text-align: center;
				justify-content: space-around;
				align-items: center;
			}

			.year {
				margin: 0 40px;
				display: flex;
				flex-direction: column;
			}

			#week {
				border-top: 1px solid #000;
				border-bottom: 1px solid #000;
				margin: auto;
				list-style-type: none;
				display: flex;
			}

			#week li {
				display: inline-block;
				text-align: center;
				flex: 1;
			}

			#ul {
				list-style-type: none;
				margin-top: 5px;
			}

			#ul li {
				display: inline-block;
				width: 40px;
				height: 21px;
				text-align: center;
				border: 1px solid #fff;
			}

			.current {
				color:#fff;
				border-radius: 50%;
				background-color: skyblue;
			}

			#ul li:hover {
				border: 1px solid red;
			}

			#prev,
			#next {
				cursor: pointer;
			}
		</style>
	</head>
	<body>
		<div class="date">
			<div class="title">
				<span id="prev">&lt;上一月</span>
				<div class="year">
					<span id="year">2021</span>
					<span id="month">月</span>
				</div>
				<span id="next">下一月&gt;</span>
			</div>
			<!-- 用ul做日历 -->
			<ul id="week">
				<li>日</li>
				<li>一</li>
				<li>二</li>
				<li>三</li>
				<li>四</li>
				<li>五</li>
				<li>六</li>
			</ul>
			<ul id="ul">

			</ul>
		</div>
	</body>
	<script type="text/javascript">

		let date = new Date()   //日期对象
		// 点击切换月份的事件
		document.getElementById('prev').addEventListener('click', function() {
			date.setMonth(date.getMonth() - 1)
			add()
		})
		document.getElementById('next').addEventListener('click', function() {
			date.setMonth(date.getMonth() + 1)
			add()
		})
		add()

		//制作日历的函数
		function add() {
			// 年
			let cYear = date.getFullYear()
			// 月
			let cMonth = date.getMonth() + 1
			// 日
			let cDay = date.getDate()

			let y = date.getMonth()+1
			// 写入年月
			document.getElementById('year').innerHTML = cYear
			document.getElementById('month').innerHTML = cMonth + '月'
			let days = new Date(cYear, cMonth, 0)	
			let n = days.getDate() // 当前月份的天数
			let week = new Date(cYear, cMonth-1, 1).getDay()  //获取这个月的第一天是周几
			
			let html = ''     //创建一个空字符串
			
			for (let i = 0; i < week; i++) {   //输出内容为空的li
				html += `<li></li>`
			}
			for (let i = 1; i <= n; i++) {   //当i与今天日期一致时，添加样式
				if (i == cDay) {
					html += '<li class="current">'+i+'</li>'
				} else {
					html += '<li>'+i+'</li>'
				}
			}


			// 将li插入ul
			document.getElementById('ul').innerHTML = html
		}
		
		// document.getElementById('ul').innerHTML = bh
	</script>
</html>
